package com.yun2.bms.controller.category;

import com.yun2.bms.dao.ICategoryDao;
import com.yun2.bms.dao.impl.CategoryDaoImpl;
import com.yun2.bms.model.Category;
import com.yun2.bms.service.ICategoryService;
import com.yun2.bms.service.impl.CategoryServiceImpl;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.stage.Modality;
import javafx.stage.Stage;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;

/**
 * author: youli
 * qq: 27855162@qq.com
 * date: 2020/5/25
 */

public class CategoryController implements Initializable {
    @FXML
    private Button btnDelete;

    @FXML
    private Pagination pager;

    @FXML
    private Button btnAdd;

    @FXML
    private Button btnEdit;

    @FXML
    private Button btnQuery;

    @FXML
    private TableColumn<Category, Category> id;

    @FXML
    private Button btnReset;

    @FXML
    private TableColumn<Category, Category> categoryName;

    @FXML
    private TableView<Category> categoryTable;

    @FXML
    private TextField tfCategoryName;

    @FXML
    void add(ActionEvent event) throws IOException {
        addNewCategory();
        clearSelection();
    }

    @FXML
    void edit(ActionEvent event) throws IOException {
        editCategory();
        clearSelection();
    }

    @FXML
    void delete(ActionEvent event) {
        deleteCategories();
        clearSelection();
    }

    @FXML
    void query(ActionEvent event) {
        //获取查询数据
        String categoryName = this.tfCategoryName.getText();
        if (StringUtils.isNotBlank(categoryName)) {
            List<Category> list = this.categoryService.getAllByCategoryName(categoryName);
            this.categoryData.clear();
            this.categoryData.addAll(list);
            this.categoryTable.setItems(categoryData);
        }
    }

    @FXML
    void reset(ActionEvent event) {
        this.categoryData.clear();
        //初始化表格
        this.tfCategoryName.setText("");
        initTable();
    }

    //存放数据库查询出来的数据列表
    private List<Category> categoryList = null;

    //图书模型数据集合，可以实时相应数据变化，无需刷新
    private ObservableList<Category> categoryData = FXCollections.observableArrayList();

    //注入CategoryDao
    private ICategoryService categoryService = new CategoryServiceImpl();

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        //设置数据表多选模式
        this.categoryTable.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
        //设置数据表行双击事件
        this.categoryTable.setRowFactory(tv -> {
            TableRow<Category> row = new TableRow<>();
            row.setOnMouseClicked(event -> {
                if (event.getClickCount() == 2 && (!row.isEmpty())) {
                    try {
                        editCategory();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
            return row;
        });
        //初始化数据表格
        initTable();
        //初始化按钮
        initButtons();

    }

    /**
     * 初始化数据表格
     */
    private void initTable() {
        this.categoryList = this.categoryService.getAll();
        this.categoryData.addAll(categoryList);
        this.categoryTable.setItems(categoryData);
    }

    /**
     * 初始化按钮
     */
    private void initButtons() {
        //默认打开表格时，没有数据被选中
        this.btnDelete.setDisable(true);
        this.btnEdit.setDisable(true);
        //初始化按钮状态
        this.categoryTable.getSelectionModel().selectedItemProperty().addListener((options, oldValue, newValue) -> {
            int number = this.categoryTable.getSelectionModel().getSelectedItems().size();
            if (number == 1) {
                this.btnEdit.setDisable(false);
                this.btnDelete.setDisable(false);
            }
            if (number > 1) {
                this.btnEdit.setDisable(true);
                this.btnDelete.setDisable(false);
            }
        });
    }

    private void addNewCategory() throws IOException {
        Stage stage = new Stage();
        stage.initModality(Modality.APPLICATION_MODAL);
        //读入布局
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/fxml/category/addCategory.fxml"));
        //创建一个与main.fxml根布局元素相同类型的布局对象root
        Parent root = fxmlLoader.load();
        AddCategoryController addCategoryController = fxmlLoader.getController();
        addCategoryController.setCategoryData(this.categoryData);
        Scene scene = new Scene(root);
        stage.setTitle("图书管理系统-添加图书分类");
        stage.setScene(scene);
        stage.setResizable(false);
        stage.show();
    }

    private void editCategory() throws IOException {
        Category category = this.categoryTable.getSelectionModel().getSelectedItem();
        Stage stage = new Stage();
        stage.initModality(Modality.APPLICATION_MODAL);
        //读入布局
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/fxml/category/editCategory.fxml"));
        //创建一个与main.fxml根布局元素相同类型的布局对象root
        Parent root = fxmlLoader.load();
        EditCategoryController editCategoryController = fxmlLoader.getController();
        editCategoryController.setCategory(category);
        Scene scene = new Scene(root);
        stage.setTitle("图书管理系统-编辑图书分类");
        stage.setScene(scene);
        stage.setResizable(false);
        stage.show();
    }

    private void clearSelection() {
        this.categoryTable.getSelectionModel().clearSelection();
        //初始化按钮
        initButtons();
    }

    private void deleteCategories() {
        Alert confirmation = new Alert(Alert.AlertType.CONFIRMATION, "是否删除选中的数据?");
        confirmation.setHeaderText("提示信息");
        confirmation.showAndWait();
        String info = "";
        if (confirmation.getResult().getButtonData().isDefaultButton()) {
            //System.out.println("OK");
            //获取选中的行
            List<Category> list = this.categoryTable.getSelectionModel().getSelectedItems();
            int ret = categoryService.delete(list);
            this.categoryData.removeAll(list);
            if (ret > 0) {
                info = "删除分类成功！";
            } else {
                info = "删除分类失败！";
            }
            //显示提示信息
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("提示信息");
            alert.setHeaderText(info);
            alert.showAndWait();
        }
    }
}
